package com.ms.tank.abstractfactory;

import com.ms.tank.common.PropertyMgr;
import com.ms.tank.common.ResourceManager;
import com.ms.tank.enums.Dir;
import com.ms.tank.enums.Group;
import com.ms.tank.game.Explode;
import com.ms.tank.game.Tank;
import com.ms.tank.game.TankFrame;

import java.awt.*;

/**
 * @Date 2021/3/18 18:39:53
 * @Author mashuai
 */
public class RectBullet extends BaseBullet {

    private int x, y;
    private Dir dir;
    //移动值
    private final int SPEED = Integer.parseInt(PropertyMgr.get("bulletSpeed").toString());
    ;
    public static int WIDTH = ResourceManager.bulletU.getWidth();
    public static int HEIGHT = ResourceManager.bulletU.getHeight();

    Rectangle rectangle = new Rectangle();

    //开火状态
    private boolean liveing = true;
    private TankFrame tankFrame = null;

    private Group group = Group.BAD;

    public RectBullet(int x, int y, Dir dir, Group group, TankFrame tankFrame) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.tankFrame = tankFrame;
        this.group = group;

        rectangle.x = this.x;
        rectangle.y = this.y;
        rectangle.height = HEIGHT;
        rectangle.width = WIDTH;

        tankFrame.bullets.add(this);
    }

    @Override
    public void paint(Graphics g) {
        //如果当前子弹不存活则移除子弹列表中的当前子弹对象
        if (!liveing) tankFrame.bullets.remove(this);
        Color c = g.getColor();
        g.setColor(Color.YELLOW);
        g.fillRect(x, y, 20, 20);
        g.setColor(c);
        move();
    }

    private void move() {
        switch (dir) {
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
        }
        rectangle.x = this.x;
        rectangle.y = this.y;

        //如果子弹命中则子弹死亡
        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
            liveing = false;
        }
    }

    //碰撞检测
    @Override
    public void collideWith(BaseTank tank) {
        //如果是一波人 则不做检测
        if (this.group == tank.getGroup()) return;
        //用一个rect来记录子弹的位置
        if (rectangle.intersects(tank.rectangle)) {
            tank.die();
            this.die();
            int ex = tank.getX() + Tank.WIDTH / 2 - Explode.WIDTH / 2;
            int ey = tank.getY() + Tank.HEIGHT / 2 - Explode.HEIGHT / 2;
            tankFrame.explodes.add(tankFrame.gameFactory.createExplode(ex, ey, tankFrame));
        }

    }

    //子弹死亡方法
    private void die() {
        this.liveing = false;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }
}
